﻿using WpfModelEditor.Core.Plugins;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace WpfModelEditor
{
    public class Program
    {
        public static string CurrentDir { get { return AppContext.BaseDirectory; } }
        public static List<IPlugin> Plugins { get; private set; }
        public static List<IIoPlugin> IoPlugins { get; private set; }
        public static void LoadPlugins()
        {
            Plugins = new List<IPlugin>();
            IoPlugins = new List<IIoPlugin>();
            var dir = Path.Combine(CurrentDir, "plugins");
            var dlls = Directory.EnumerateFiles(dir, "*.dll");
            foreach (var dll in dlls)
            {
                try
                {
                    var asm = Assembly.LoadFile(dll);
                    var types = asm.GetTypes().Where(p => !p.IsInterface && !p.IsAbstract && p.IsPublic && typeof(IBasePlugin).IsAssignableFrom(p)).ToList();
                    foreach (var type in types)
                    {
                        var plugin = Activator.CreateInstance(type) as IBasePlugin;
                        if (plugin is IIoPlugin)
                            IoPlugins.Add(plugin as IIoPlugin);
                        else
                            Plugins.Add(plugin as IPlugin);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
            }
            Plugins = Plugins.OrderBy(p => p.Order).ToList();
            IoPlugins = IoPlugins.OrderBy(p => p.Order).ToList();
        }
        [STAThread]
        public static int Main(string[] args)
        {
            var app = new App();
            LoadPlugins();
            app.DispatcherUnhandledException += App_DispatcherUnhandledException;
            app.InitializeComponent();
            return app.Run();
        }

        private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            MessageBox.Show(e.Exception.Message);
        }
    }
}
